package com.jhyspringcloud.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(value = 2)
public class AuthGlobalFilter implements GlobalFilter {

    /**
     * @return
     * @author: robert
     * @description: 简单判断请求参数里是否有 authString = yes,如果有，放行，反之过滤
     * @date: 2021/9/10 16:51
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取参数authString
        ServerHttpRequest request = exchange.getRequest();
        String val = String.valueOf(request.getQueryParams().get("authString"));
        //2.判断
        if (val.contains("yes")) {
            return chain.filter(exchange);
        }
        //3.不成就阻拦
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}
